# coding: UTF-8
'''
Created on 2011/06/10

@author: yang_wanjun
'''
from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import gettext_lazy as _

TASK_STATUS_ADD = 1
TASK_STATUS_UPDATE = 2
TASK_STATUS_DELETE = 3
TASK_STATUS_COMPLETE = 0

class TaskManager(models.Manager):
    def add_task(self, obj):
        ctype = ContentType.objects.get_for_model(obj)
        self.create(content_type=ctype, object_pk=obj.pk, status=TASK_STATUS_ADD)
    
    def update_task(self, obj):
        ctype = ContentType.objects.get_for_model(obj)
        task = self.get(content_type=ctype, object_pk=obj.pk)
        task.status = TASK_STATUS_UPDATE
        task.save()
        
    def delete_task(self, obj):
        ctype = ContentType.objects.get_for_model(obj)
        task = self.get(content_type=ctype, object_pk=obj.pk)
        task.status = TASK_STATUS_DELETE
        task.save()
        
    def get_add_tasks(self):
        return super(TaskManager, self).get_query_set().filter(status=TASK_STATUS_ADD)
    
    def get_update_tasks(self):
        return super(TaskManager, self).get_query_set().filter(status=TASK_STATUS_UPDATE)
    
    def get_delete_tasks(self):
        return super(TaskManager, self).get_query_set().filter(status=TASK_STATUS_DELETE)

class Task(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_pk = models.PositiveIntegerField(_('object id'), db_index=True)
    content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
    # 索引状态(0:完成，1:添加，2:修改，3:删除)
    status = models.IntegerField()
    
    objects = TaskManager()
    
    class Meta:
        unique_together = (('content_type', 'object_pk'),)




